﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using yaTDL.Core.MVVM;
using yaTDL.Properties;
using System.Threading;

namespace yaTDL
{
    /// <summary>
    /// Interaction logic for MainPage.xaml
    /// </summary>
    public partial class MainPage : Page
    {
        public MainPage()
        {

            

            InitializeComponent();

            this.SizeChanged += new SizeChangedEventHandler(page_SizeChanged);


            gridColumn_SavedSearchesMinWidth = this.gridColumn_SavedSearches.MinWidth;
            
            this.gridColumn_SavedSearches.MinWidth = 0;


            //subsribe to events from the ViewModel that make necessary some adjustments in the view
            this.Loaded += (s,e) =>
            {
                (this.DataContext as MainPageViewModel).SearchViewModel.SavedSearches.CollectionChanged += (s2, e2) => { adjustSavedSearchedColumnWidth(); };
                (this.DataContext as MainPageViewModel).SearchViewModel.PropertyChanged += (s3, e3) => 
                {
                    if (e3.PropertyName == "SavedSearches")
                    {
                        adjustSavedSearchedColumnWidth();
                    }
                };

                gridColumn_SavedSearchesWidthCache = this.gridColumn_SavedSearches.ActualWidth;
                adjustSavedSearchedColumnWidth();

            };


            this.DataContextChanged += (s, e) =>
            {
                if (UISettings.Default.Projectlist_SelectedIndex > (this.DataContext as MainPageViewModel).ProjectListViewModel.Projects.Count - 1)
                {
                    UISettings.Default.Projectlist_SelectedIndex = (this.DataContext as MainPageViewModel).ProjectListViewModel.Projects.Count - 1;
                }
                adjustSavedSearchedColumnWidth();
            };



            
                      
        }

        #region Layout- and other UI-Workarounds


        /// <summary>
        /// Temporarily stores the width of gridColumn_SavedSearches, so it can be restored after it the "Saved Searches"-list is no longer hidden
        /// </summary>
        private double gridColumn_SavedSearchesWidthCache = 0;

        private double gridColumn_SavedSearchesMinWidth;


        /// <summary>
        /// Adjusts the MaxWidth and With properties of the "Saved Searches" list in the search tab based on the current number of saved searches.
        /// </summary>
        private void adjustSavedSearchedColumnWidth()
        {

            if (this.DataContext == null || !(this.DataContext is MainPageViewModel) || this.ActualWidth == 0)
                return;



            if ((this.DataContext as MainPageViewModel).SearchViewModel.SavedSearches.Any())
            {
                gridColumn_SavedSearches.MinWidth = gridColumn_SavedSearchesMinWidth;
                gridColumn_SavedSearches.MaxWidth = this.ActualWidth - (gridColumn_SavedSearches.Parent as Grid).ColumnDefinitions[2].MinWidth;

                if (this.gridColumn_SavedSearches.ActualWidth < gridColumn_SavedSearchesWidthCache)
                {
                    gridColumn_SavedSearches.Width = (GridLength)new GridLengthConverter().ConvertFrom(gridColumn_SavedSearchesWidthCache);
                }
                
            }

            else
            {

                gridColumn_SavedSearchesWidthCache = gridColumn_SavedSearches.ActualWidth;

                gridColumn_SavedSearches.MinWidth = 0;
                gridColumn_SavedSearches.Width = (GridLength)new GridLengthConverter().ConvertFrom(0);
                gridColumn_SavedSearches.MaxWidth = 0;

            }

        }

        /// <summary>
        /// Adjusts the MaxWidth of the project-list and the "Saved Searches" list after the page's size has changed.
        /// </summary>
        /// <param name="sender">The sender of the SizeChanged event.</param>
        /// <param name="e">The event's SizeChangedEventArgs</param>
        private void page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            grid_ProjectsTaskList.ColumnDefinitions[0].MaxWidth = this.ActualWidth - grid_ProjectsTaskList.ColumnDefinitions[1].ActualWidth - grid_ProjectsTaskList.ColumnDefinitions[2].MinWidth - 10;

            if (gridColumn_SavedSearches.MaxWidth != 0)
            {
                gridColumn_SavedSearches.MaxWidth = this.ActualWidth - (gridColumn_SavedSearches.Parent as Grid).ColumnDefinitions[2].MinWidth;
            }
        }        

        /// <summary>
        /// Focuses the searchBox if the search-tab is selected.
        /// </summary>
        /// <param name="sender">The sender of the SelectionChanged event.</param>
        /// <param name="e">The event's SelectionChangedEventArgs</param>
        private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabControl1.SelectedIndex == 1)
            {

                if (!searchBox.IsFocused)
                {
                    searchBox.Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(delegate()
                    {
                        searchBox.Focus();
                    }));
                }

                if (!String.IsNullOrEmpty(searchBox.Text))
                {
                    searchBox.SelectAll();
                }                
            }
        }


        #endregion Layout- and other UI-Workarounds

        private void GridSplitter_DragCompleted(object sender, System.Windows.Controls.Primitives.DragCompletedEventArgs e)
        {
            gridColumn_SavedSearchesWidthCache = this.gridColumn_SavedSearches.ActualWidth;
        }

    }
}
